<template>
  <el-dialog
    :visible="dialogVisible"
    :close-on-click-modal="false"
    title="上传文件"
    width="500px"
    :before-close="cancelClose"
  >
    <el-form label-width="calc(100% - 100px)" label-position="left">
      <el-form-item label="1：上传填写好的会议纪要:">
        <el-upload
          action="#"
          :multiple="false"
          ref="upload"
          :on-change="handleChange"
          :file-list="fileList"
          :auto-upload="false"
          :headers="headers"
          :http-request="uploadSubmit"
          :before-remove="handleRemove"
          accept=".xlsx, .pdf, .doc, .docx, .xls"
        >
          <el-button slot="trigger" type="primary" style="border-radius: 20px"
            >本地文件</el-button
          >
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancelClose">取 消</el-button>
      <el-button type="primary" @click="uploadSubmit">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  findFileByMeetingId,
  insertMeetingFile,
  deleteMeetingFile
} from '@/apis/meetingMinutes.js'
import { getRealToken } from '@/utils/util'

export default {
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      headers: {
        Authorization: getRealToken()?.insightToken
      },
      rowData: {},
      delArr: []
    }
  },
  mounted() {},
  methods: {
    async getFilelList(meetingId) {
      this.fileList = []
      let res = await findFileByMeetingId({ meetingId })
      if (res.code === 200) {
        res.data.map((item) => {
          this.fileList.push({
            name: item.fileName,
            url: item.url,
            id: item.id,
            meetingId: item.meetingId
          })
        })
      } else {
        this.$message.warning(res.data)
      }
    },
    cancelClose() {
      this.dialogVisible = false
      this.fileList = []
    },
    handleRemove(file, fileList) {
      return new Promise((response, reject) => {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((res) => {
            if (res === 'confirm') {
              if (file.id) {
                this.delArr.push(file.id)
              }
              let delIndex = this.fileList.findIndex((item) => {
                if (item.id) {
                  return item.id === file.id
                }
              })
              this.fileList.splice(delIndex, 1)
            } else {
              return reject()
            }
          })
          .catch(() => {
            return reject()
          })
      })
    },
    handleChange(file, fileList) {
      let idx = this.fileList.findIndex((ele) => {
        return ele.raw
      })
      if (idx > -1) {
        this.fileList.splice(idx, 1)
      }
      this.fileList.push(file)
    },
    async uploadSubmit() {
      const _this = this
      // 处理删除操作
      const deletePromises = []
      if (_this.delArr && _this.delArr.length > 0) {
        _this.delArr.forEach((id) => {
          deletePromises.push(
            deleteMeetingFile({ id }).then((res) => {
              if (res.code === 200 && res.data > 0) {
                return true
              } else {
                return false
              }
            })
          )
        })
      }
      // 处理文件上传
      const uploadPromises = []
      if (_this.fileList && _this.fileList.length > 0) {
        _this.fileList.forEach((ele) => {
          if (ele.raw) {
            const fd = new FormData()
            fd.append('meetingId', _this.rowData.id)
            fd.append('file', ele.raw)
            uploadPromises.push(
              insertMeetingFile(fd).then((res) => {
                if (res.code === 200 && res.data > 0) {
                  return true
                } else {
                  return false
                }
              })
            )
          }
        })
      }

      let res = await Promise.all([...deletePromises, ...uploadPromises])
      if (!res.includes(false)) {
        this.$message.success('保存成功！')
        _this.cancelClose()
        _this.$parent.search()
      } else {
        this.$message.warning('保存失败！')
      }
    },
    show(row) {
      this.dialogVisible = true
      this.getFilelList(row.id)
      this.rowData = row
    },
    // 成功失败日志
    logSuccessOrError(data, type) {
      this.addLog(1, this.elDialogTitle == '编辑' ? 'edit' : 'add', data, type)
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep {
  .el-upload-list.el-upload-list--text {
    // position: absolute;
    position: relative;
    left: -360px;
  }
  .el-dialog__title {
    font-weight: bold;
  }
  .el-upload-list__item {
    width: 350px;
    background-color: rgba(24, 144, 255, 0.09803921568627451);
  }
  .el-upload-list__item-name {
    color: #1890ff;
  }
  .el-upload-list__item.is-success.focusing .el-icon-close-tip {
    display: none !important;
  }
}
</style>
